<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { SegmentGroup } from '@ark-ui/vue/segment-group';
import { useI18n } from 'vue-i18n';
import { useFetch } from '@/home/hooks/fetch';
import { useAppStore } from '@/home/stores/app';
import defaultImg from '@/home/assets/home/default.png';
import { useToast } from '@/home/hooks/toast';
import { gotoLoginForClient } from '@/common/utils/auth';
import Pagination from '@/home/components/Pagination.vue';
import CommentInput from './CommentInput.vue';
import CommentPost from './CommentPost.vue';

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['change']);

const PAGE_SIZE = 10;

const toaster = useToast()
const appStore = useAppStore();
const { $fetch } = useFetch();
const { t } = useI18n();

const currentComment = ref('');
const pages = ref(1);
const listing = ref<Record<string, any>[]>([]);
const total = ref(0);
const commentTotal = ref(0);
const showInputState = ref(false);
const orderBy = ref('1');
const sending = ref(false);

const login = () => {
  gotoLoginForClient();
};

const refresh = async () => {
  const { isSuccess, data } = await $fetch('/comment/page', {
    method: 'post',
    data: {
      informationId: props.id,
      pageNum: pages.value,
      pageSize: PAGE_SIZE,
      orderBy: orderBy.value,
    },
  });

  if (isSuccess) {
    listing.value = data?.records?.map((comment: any) => ({
      ...comment,
      showReplyForm: false,
    })) ?? [];
    total.value = data?.total ?? 0;
    commentTotal.value = data?.commentTotal ?? 0;
  }
};

const handlePageChange = (index: number) => {
  pages.value = index;
  refresh();
};

const toggleReplyForm = (comment: any) => {
  if (!appStore.user.id) {
    login();
    return;
  }
  if (!comment.commentText) {
    comment.commentText = '';
  }
  comment.showReplyForm = !comment.showReplyForm;
};

const sendComment = async (content: string, level: number, parentId = '') => {
  if (!content.trim()) {
    return false;
  }

  sending.value = true;

  const { isSuccess, msg } = await $fetch('/comment/create', {
    method: 'post',
    data: {
      informationId: props.id,
      commentContent: content.trim(),
      level,
      commentParentId: parentId,
    },
  });

  sending.value = false;

  if (isSuccess) {
    emit('change');
    refresh();
  }
  else {
    toaster.error(msg);
  }

  return isSuccess;
};

const createComment = async (content: string) => {
  const isSuccess = await sendComment(content, 1);

  if (isSuccess) {
    toaster.success(t('home.explore.comments.createSuccess'));
    currentComment.value = '';
  }
};

const replyComment = async (comment: Record<string, any>) => {
  const isSuccess = await sendComment(comment.commentText, 2, comment.id);

  if (isSuccess) {
    toaster.success(t('home.explore.comments.replySuccess'));
    comment.commentText = '';
  }
}

const removeComment = async (id: string) => {
  const { isSuccess } = await $fetch('/comment/delete', {
    method: 'post',
    data: {
      id,
    },
  });

  if (isSuccess) {
    toaster.success(t('home.explore.comments.deleteSuccess'));

    emit('change');

    refresh();
  }
};

const likeComment = async (comment: Record<string, any>) => {
  const { isSuccess } = await $fetch('/comment/like', {
    method: 'post',
    autoGotoLogin: true,
    data: {
      id: comment.id,
    },
  });

  if (isSuccess) {
    // 可以不从接口刷新数据，提高用户体验
    if (comment.isUserLike == 1) {
      // 取消成功
      comment.isUserLike = 0;
      comment.commentLikeCount--;
    }
    else {
      comment.isUserLike = 1;
      comment.commentLikeCount++;
    }
  }
};

watch(orderBy, () => {
  refresh();
});

watch(() => props.id, () => {
  showInputState.value = false;
  refresh();
});

onMounted(() => {
  refresh();
});
</script>

<template>
  <div class="component-comment">
    <div class="rounded-4 bg-white p-20">
      <div class="flex-y-center gap-x-12" v-if="!appStore.user.id">
        <div class="i-icons:default-avatar size-40"></div>
        <i18n-t keypath="home.explore.comments.headFor" scope="global" tag="div" class="text-14 text-#8B8B8B">
          <template #action>
            <a href="javascript:;" class="text-#3D7CFA hover:(underline)" @click="login">{{ $t('home.explore.comments.login') }}</a>
          </template>
        </i18n-t>
      </div>

      <div class="flex gap-x-12" v-else>
        <div class="flex-shrink-0">
          <img :data-src="appStore.user.photo || defaultImg" :alt="appStore.user.nickname" class="lozad block size-40 border-1 border-#ebebeb rounded-full">
        </div>

        <div class="flex-grow overflow-hidden">
          <div class="cursor-pointer text-14 text-#8B8B8B leading-40" @click="showInputState = true" v-if="!showInputState">
            {{ $t('home.explore.comments.tips') }}
          </div>
          <template v-else>
            <div class="truncate-ellipsis text-14 text-#292929 leading-40"><span>{{ appStore.user.nickname }}</span></div>
            <CommentInput
              v-model="currentComment"
              :disabled="sending"
              :placeholder="$t('home.explore.comments.tips')"
              @submit="createComment(currentComment)"
              @blur="showInputState = false"
            />
          </template>
        </div>
      </div>
    </div>

    <template v-if="listing?.length">
      <div class="mt-40">
        <div v-if="commentTotal" class="relative h-22 flex items-center justify-center">
          <h2 class="text-16 text-#292929 font-medium leading-22">{{ $t('home.explore.comments.allComments', { total: commentTotal }) }}</h2>

          <div class="absolute right-0">
            <SegmentGroup.Root v-model="orderBy" class="flex text-14 text-#8B8B8B leading-22">
              <SegmentGroup.Item value="1" class="bg-transparent data-[state=unchecked]:(cursor-pointer) data-[state=checked]:(text-#3D7CFA)">
                <SegmentGroup.ItemText>{{ $t('home.explore.comments.latest') }}</SegmentGroup.ItemText>
                <SegmentGroup.ItemControl />
                <SegmentGroup.ItemHiddenInput />
              </SegmentGroup.Item>
              <span>｜</span>
              <SegmentGroup.Item value="2" class="bg-transparent data-[state=unchecked]:(cursor-pointer) data-[state=checked]:(text-#3D7CFA)">
                <SegmentGroup.ItemText>{{ $t('home.explore.comments.hottest') }}</SegmentGroup.ItemText>
                <SegmentGroup.ItemControl />
                <SegmentGroup.ItemHiddenInput />
              </SegmentGroup.Item>
            </SegmentGroup.Root>
          </div>
        </div>

        <ul class="mt-20">
          <li class="mt-12 rounded-4 bg-white p-20 first:(mt-0)" v-for="comment in listing" :key="comment.id">
            <CommentPost
              :avatar="comment.createUserUrl"
              :nickname="comment.createNickName"
              :time="comment.createTime"
              :content="comment.commentContent"
              :reply-total="comment.commentChildrenCount"
              :like-total="comment.commentLikeCount"
              :show-action="comment.commentState == 1"
              :is-author="comment.isAuthor == 1"
              :is-like="comment.isUserLike == 1"
              :is-delete="comment.isToDelete == 1"
              @reply="toggleReplyForm(comment)"
              @like="likeComment(comment)"
              @remove="removeComment(comment.id)"
            >
              <template #input>
                <div class="mt-8 flex gap-x-12 border-1 border-#FAFAFA p-20" v-if="comment.showReplyForm">
                  <div class="flex-shrink-0">
                    <img :data-src="appStore.user.photo || defaultImg" :alt="appStore.user.nickname" class="lozad block size-40 border-1 border-#ebebeb rounded-full">
                  </div>
                  <div class="flex-grow overflow-hidden">
                    <div class="h-40 text-14 leading-40">
                      <span class="inline-block max-w-45% truncate text-#292929">{{ appStore.user.nickname }}</span>
                      <span class="ml-8 inline-block truncate text-#8B8B8B">{{ $t('home.explore.comments.reply') }}</span>
                      <span class="ml-8 inline-block max-w-45% truncate text-#8B8B8B">{{ comment.createNickName }}</span>
                    </div>
                    <CommentInput v-model="comment.commentText" :disabled="sending" :placeholder="$t('home.explore.comments.tips')" @submit="replyComment(comment)" />
                  </div>
                </div>
              </template>

              <template #child>
                <ul v-if="comment.commentVOS">
                  <template v-for="(commentChild, childIndex) in comment.commentVOS" :key="commentChild.id">
                    <li class="mt-20" v-if="childIndex < 3 || comment.showAll">
                      <CommentPost
                        :avatar="commentChild.createUserUrl"
                        :nickname="commentChild.createNickName"
                        :reply-nickname="commentChild.replyNickName"
                        :time="commentChild.createTime"
                        :content="commentChild.commentContent"
                        :reply-total="commentChild.commentChildrenCount"
                        :like-total="commentChild.commentLikeCount"
                        :show-action="commentChild.commentState == 1"
                        :is-author="commentChild.isAuthor == 1"
                        :is-like="commentChild.isUserLike == 1"
                        :is-delete="commentChild.isToDelete == 1"
                        @reply="toggleReplyForm(commentChild)"
                        @like="likeComment(commentChild)"
                        @remove="removeComment(commentChild.id)"
                      >
                        <template #input>
                          <div class="mt-8 flex gap-x-12 border-1 border-#FAFAFA p-20" v-if="commentChild.showReplyForm">
                            <div class="flex-shrink-0">
                              <img :data-src="appStore.user.photo || defaultImg" :alt="appStore.user.nickname" class="lozad block size-40 border-1 border-#ebebeb rounded-full">
                            </div>
                            <div class="flex-grow overflow-hidden">
                              <div class="h-40 text-14 leading-40">
                                <span class="inline-block max-w-45% truncate text-#292929">{{ appStore.user.nickname }}</span>
                                <span class="ml-8 inline-block truncate text-#8B8B8B">{{ $t('home.explore.comments.reply') }}</span>
                                <span class="ml-8 inline-block max-w-45% truncate text-#8B8B8B">{{ commentChild.createNickName }}</span>
                              </div>
                              <CommentInput v-model="commentChild.commentText" :disabled="sending" :placeholder="$t('home.explore.comments.tips')" @submit="replyComment(commentChild)" />
                            </div>
                          </div>
                        </template>

                        <template #child>
                          <button type="button" class="mt-20 bg-transparent text-14 text-#8B8B8B hover:(text-#3D7CFA)" @click="comment.showAll = true" v-if="!comment.showAll && comment.commentVOS.length > 3 && childIndex === 2">
                            {{ $t('home.explore.comments.viewAllReply', { total: comment.commentVOS.length }) }}
                          </button>
                        </template>
                      </CommentPost>
                    </li>
                  </template>
                </ul>
              </template>
            </CommentPost>
          </li>
        </ul>
      </div>

      <Pagination class="data-[total-pages=gt1]:(mt-32)" :count="total" :page="pages" :page-size="PAGE_SIZE" @change="handlePageChange" />
    </template>
  </div>
</template>

<style lang="scss" scoped>
</style>
